<?php
/**
 * Created by PhpStorm.
 * User: GIGABYTE
 * Date: 2016/6/21
 * Time: 17:51
 */

namespace MMC\Statistics\BaiDu\Libs;


class RsaPublicEncrypt
{
    private $publicKey;

    private $path;

    public function __construct($path = __DIR__)
    {
        $this->path = $path;
    }

    public function setPublicKey()
    {
        if (is_resource($this->publicKey)) {
            return true;
        }

        $file = $this->path . DIRECTORY_SEPARATOR . 'apiPub.key';

        $key = file_get_contents($file);

        $this->publicKey = openssl_pkey_get_public($key);
    }

    public function pubEncrypt($string)
    {
        if (!is_string($string)) {
            return null;
        }

        $this->setPublicKey();

        $result = openssl_public_encrypt($string, $encrypted, $this->publicKey);

        return $result ? $encrypted : null;
    }

}